package blog

import (
	"fmt"
	"strings"
)

type Status int8

const (
	DRAFT Status = iota
	PUBLISHED
)

var (
	// 状态字符串映射
	StatusValueMap = map[Status]string{
		DRAFT:     "draft",
		PUBLISHED: "published",
	}
)

// 将状态字符串转化成Status
func ParseStatusFromString(status string) (*Status, error) {
	for k, v := range StatusValueMap {
		if v == status {
			return &k, nil
		}
	}
	return nil, fmt.Errorf("not supprot %s", status)
}

func (s Status) String() string {
	return StatusValueMap[s]
}

func (s Status) MarshalJSON() ([]byte, error) {
	v := StatusValueMap[s]
	// 加上""
	v = fmt.Sprintf(`"%s"`, v)
	return []byte(v), nil
}

func (s *Status) UnmarshalJSON(data []byte) error {
	str := string(data)
	// 去掉""
	str = strings.Trim(str, `"`)
	for k, v := range StatusValueMap {
		if v == str {
			*s = k
		}
	}
	return nil
}

type UpdateMode string

const (
	PATCH UpdateMode = "patch"
	PUT   UpdateMode = "put"
)
